//
//  ResumeViewController.m
//  BombAbility
//
//  Created by oscar chinellato on 28/02/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "BombAbilityAppDelegate.h"
#import "GameViewController.h"
#import "Math.h"

#define kFilteringFactor 0.05


@implementation GameViewController

@synthesize CurrentXLabel;
@synthesize CurrentYLabel;
@synthesize CurrentZLabel;

@synthesize SavedXLabel;
@synthesize SavedYLabel;
@synthesize SavedZLabel;

@synthesize CompassXLabel;
@synthesize CompassYLabel;
@synthesize CompassZLabel;

@synthesize calibrationOffset;
@synthesize locationManager;


/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	
	[super viewDidLoad];
	
	UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer];
	accelerometer.delegate = self;
	accelerometer.updateInterval =  kUpdateInterval;
	
	self.locationManager = [[[CLLocationManager alloc] init] autorelease];
	
	//check if the hardware has a compass
	if (locationManager.headingAvailable == NO) {
		// No compass is available. This application cannot function without a compass, 
        // so a dialog will be displayed and no magnetic data will be measured.
        
		self.locationManager = nil;
        UIAlertView *noCompassAlert = [[UIAlertView alloc] initWithTitle:@"No Compass!" message:@"This device does not have the ability to measure magnetic fields." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [noCompassAlert show];
        [noCompassAlert release];
		
	} else {
        // heading service configuration
        locationManager.headingFilter = kCLHeadingFilterNone;
        
        // setup delegate callbacks
        locationManager.delegate = self;
        
        // start the compass
        [locationManager startUpdatingHeading];
    }
	
	
   
}

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
	
	currentRawReadingX = [self roundToWithValue:acceleration.x DigitsAfterPoint:1];
	currentRawReadingY = [self roundToWithValue:acceleration.y DigitsAfterPoint:1];
	currentRawReadingZ = [self roundToWithValue:acceleration.z DigitsAfterPoint:1];
	
	[CurrentXLabel setText: [NSString stringWithFormat:@"Valore X: %f", currentRawReadingX]]; 
	[CurrentYLabel setText: [NSString stringWithFormat:@"Valore Y: %f", currentRawReadingY]];
	[CurrentZLabel setText: [NSString stringWithFormat:@"Valore Z: %f", currentRawReadingZ]];
	
	[self CorrectValueX: currentRawReadingX CorrectValueY: currentRawReadingY CorrectValueZ: currentRawReadingZ];
	
}

-(float)roundToWithValue:(float)value DigitsAfterPoint:(int)dap {
	
	float aft = pow(10,dap);
	return round(value * aft)/aft;
}

- (void)resetAccelerometer {
	
	startPosX = currentRawReadingX;
	startPosY = currentRawReadingY;
	startPosZ = currentRawReadingZ;
	
	[SavedXLabel  setText: [NSString stringWithFormat:@"Salvato %f", startPosX]];
	[SavedYLabel  setText: [NSString stringWithFormat:@"Salvato %f", startPosY]];
	[SavedZLabel  setText: [NSString stringWithFormat:@"Salvato %f", startPosZ]];
	
}

- (void)CorrectValueX:(float)xValue CorrectValueY:(float)yValue CorrectValueZ:(float)zValue {
	
	float correctedValueX = xValue - startPosX;
	float correctedValueY = yValue - startPosY;
	float correctedValueZ = zValue - startPosZ;
	
	[CorrectedXLabel setText: [NSString stringWithFormat:@"Corretto %.1f", correctedValueX]];
	[CorrectedYLabel setText: [NSString stringWithFormat:@"Corretto %.1f", correctedValueY]];
	[CorrectedZLabel setText: [NSString stringWithFormat:@"Corretto %.1f", correctedValueZ]];
	
}

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)heading {
	
    // Update the labels with the raw x, y, and z values.
	[CompassXLabel setText:[NSString stringWithFormat:@"TeslaX %.1f", heading.x]];
	[CompassYLabel setText:[NSString stringWithFormat:@"TeslaY %.1f", heading.y]];
	[CompassZLabel setText:[NSString stringWithFormat:@"TeslaZ %.1f", heading.z]];
    
    // Compute and display the magnitude (size or strength) of the vector.
	//      magnitude = sqrt(x^2 + y^2 + z^2)
}

// This delegate method is invoked when the location managed encounters an error condition.

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
	
    if ([error code] == kCLErrorDenied) {
        // This error indicates that the user has denied the application's request to use location services.
        [manager stopUpdatingHeading];
    } else if ([error code] == kCLErrorHeadingFailure) {
        // This error indicates that the heading could not be determined, most likely because of strong magnetic interference.
    }
}


// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
	
	// Stop the compass
	[locationManager stopUpdatingHeading];
	[locationManager release];
	
    [super dealloc];
}


@end
